# 2021-8-28 10:50 修改返回格式，增加字段
from rest_framework.decorators import api_view
from questionnaire.models import *
from rest_framework.response import Response
from rest_framework import status


@api_view(['POST', ])
def showJudge(request):
    wid = request.data.get('qid')
    sid = request.data.get('sid')
    if wid and sid:
        wj = Questionnaire.objects.filter(id=wid).first()
        submit = Submit.objects.filter(id=sid).first()
        if wj and submit and wj.type == 'exam':
            # 问卷标题、填写时间、完成时间、姓名、学号
            # 找到所有题目
            questions = Question.objects.filter(wjId=wid)
            # 姓名题和学号题对应的题目id
            q_name_id = questions[0].id
            q_number_id = questions[1].id
            # 查询sid所提交的姓名和学号
            print(questions)
            print(q_name_id)
            print(q_number_id)
            tmp_name = Answer.objects.filter(questionId=q_name_id).filter(submitId=sid).first()
            tmp_number = Answer.objects.filter(questionId=q_number_id).filter(submitId=sid).first()
            name = ''
            number = ''
            if tmp_name:
                name = Answer.objects.filter(questionId=q_name_id).filter(submitId=sid).first().answerText
            if tmp_number:
                number = Answer.objects.filter(questionId=q_number_id).filter(submitId=sid).first().answerText
            # 计算答题用时
            if submit.useTime:
                t = submit.useTime
                s = str(int(t % 60))
                m = str(int((t // 60) % 60))
                h = str(int(t // 3600))
            else:
                s, m, h = '-', '-', '-'
            use_time = h + '时' + m + '分' + s + '秒'

            info = {
                'questionnaire_title': wj.title,
                'submit_time': submit.submitTime,
                'use_time': use_time,
                'name': name,
                'number': number,
                'total_score': 0,
                'questions': []
            }
            for q in questions[2:]:
                # correct_option_title = Options.objects.filter(id=q.correct_option).first().title
                a = Answer.objects.filter(questionId=q.id).filter(submitId=sid).first()
                # options = Options.objects.filter(questionId=q.id)
                d_q = {
                    'question_title': q.title,
                    'question_type': q.type,
                    'row': q.row,
                    'must': q.must,
                    'remark': q.remark,
                    'score': q.score
                }
                if q.type == 'single':
                    options = list(Options.objects.filter(questionId=q.id).values_list('title', flat=True))
                    d_q['options'] = options
                    correct_option_title = Options.objects.filter(id=q.correct_option).first().title
                    answer = Options.objects.filter(id=a.answer).first().title
                    d_q['correct'] = [correct_option_title]
                    d_q['answer'] = [answer]
                    if d_q['correct'] == d_q['answer']:
                        d_q['grade'] = d_q['score']
                        d_q['right'] = '回答正确'
                    else:
                        d_q['grade'] = 0
                        d_q['right'] = '回答错误'
                elif q.type == 'fill':
                    d_q['correct'] = [q.correct_answer]
                    d_q['answer'] = [a.answerText]
                    if d_q['correct'] == [None]:  # 木有答案
                        d_q['grade'] = 0
                        d_q['right'] = '人工评分'
                    elif d_q['correct'] != d_q['answer']:
                        d_q['grade'] = 0
                        d_q['right'] = '回答错误'
                    else:
                        d_q['grade'] = d_q['score']
                        d_q['right'] = '回答正确'
                elif q.type == 'multi':
                    options = list(Options.objects.filter(questionId=q.id).values_list('title', flat=True))
                    d_q['options'] = options
                    correct_option_titles = list(Options.objects.filter(questionId=q.id).filter(is_correct=True).values_list('title', flat=True).distinct())
                    ans_id = list(Answer.objects.filter(questionId=q.id).filter(submitId=sid).values_list('answer', flat=True).distinct())
                    answers = list(Options.objects.filter(questionId=q.id).filter(id__in=ans_id).values_list('title', flat=True).distinct())
                    d_q['correct'] = correct_option_titles
                    d_q['answer'] = answers
                    if len(d_q['correct']) != 0 and set(d_q['answer']) <= set(d_q['correct']) and len(d_q['answer']) != 0:
                        if set(d_q['answer']) < set(d_q['correct']):
                            d_q['grade'] = d_q['score'] * (len(d_q['answer']) / len(d_q['correct']))
                            d_q['right'] = '部分正确'
                        elif set(d_q['answer']) == set(d_q['correct']):
                            d_q['grade'] = d_q['score']
                            d_q['right'] = '回答正确'
                    else:
                        d_q['grade'] = 0
                        d_q['right'] = '回答错误'
                info['total_score'] += d_q['grade']
                d_q['grade'] = "%.2f" % d_q['grade']
                info['questions'].append(d_q)
            info['total_score'] = "%.2f" % info['total_score']
            response = {
                'code': 0,
                'msg': 'success',
                'info': info
            }
        else:
            response = {
                'code': 2,
                'msg': '数据库中查找不到对应id的问卷/提交，或该问卷不是考试问卷'
            }
    else:
        response = {
            'code': 1,
            'msg': '问卷id/sid无效或为空'
        }
    return Response(response, status=status.HTTP_200_OK)
